package com.cuitrip.business.order;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cuitrip.apiservice.OrderBusiness;
import com.cuitrip.apiservice.model.ApiManager;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.business.order.model.CancelReason;
import com.cuitrip.business.order.model.OrderItem;
import com.cuitrip.business.order.model.RefundInfo;
import com.cuitrip.business.setting.SubmitSuccessActivity;
import com.cuitrip.business.setting.model.SubmitSuccessModel;
import com.cuitrip.business.tripservice.ServiceDetailActivity;
import com.cuitrip.business.tripservice.ui.IconTextView;
import com.cuitrip.business.user.model.CtUserInfo;
import com.cuitrip.business.webview.H5UrlMaker;
import com.cuitrip.business.webview.proxy.WebViewProxy;
import com.cuitrip.component.AutoMatchListView;
import com.cuitrip.im.CtInfoNotificationMsgItemProvider;
import com.cuitrip.im.model.CTInformationNotificationMessage;
import com.cuitrip.im.proxy.CtRongInfoProxy;
import com.cuitrip.presenter.FeeRenderData;
import com.cuitrip.presenter.RefundInfoViewHolder;
import com.cuitrip.service.R;
import com.cuitrip.util.ResourceUtil;
import com.cuitrip.util.time.InputTime;
import com.cuitrip.util.time.OutputTime;
import com.cuitrip.util.time.TimeUtil;
import com.cuitrip.util.track.TrackUtil;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragmentActivity;
import com.lab.jumper.Jumper;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.utils.ImageHelper;
import com.lab.utils.LogHelper;
import com.lab.utils.MessageUtils;
import com.lab.utils.Utils;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;


/**
 * Created on 7/20.
 */
public class CancelOrderActivity extends CustomUiFragmentActivity implements View.OnClickListener, IProxyCallback {

    public static final String ORDER_KEY = "CancelOrderActivity.ORDER_KEY";

    @Bind(R.id.money_type)
    TextView moneyType;

    @Bind(R.id.service_pic)
    ImageView servicePic;

    @Bind(R.id.ct_service_name_tv)
    TextView serviceName;

    @Bind(R.id.author_name)
    TextView authorName;

    @Bind(R.id.simple_info)
    TextView simpleInfo;

    @Bind(R.id.refund_term)
    RelativeLayout refundTerm;

    @Bind(R.id.listView_reason)
    AutoMatchListView listViewReasons;

    @Bind(R.id.title_layout)
    RelativeLayout titleLayout;

    @Bind(R.id.detail1)
    RelativeLayout paidFee;

    @Bind(R.id.detail2)
    RelativeLayout cancellationFee;

    @Bind(R.id.icon)
    IconTextView arrowIcon;

    @Bind(R.id.other_reason)
    EditText otherReason;

    @Bind(R.id.cancel_order)
    TextView cancelOrder;

    @Bind(R.id.ct_service_info_v)
    LinearLayout serviceInfoLayout;

    @Bind(R.id.service_layout)
    RelativeLayout mServiceLayout;
    RefundInfoViewHolder servicePartViewHolder = new RefundInfoViewHolder();
    boolean flag = true;
    private ApiProxy mApiProxy = new ApiProxy(this);
    private String type;
    private OrderItem mOrderInfo;
    private TermSelectAdapter termSelectAdapter;
    private String msg;
    private ArrayList<ReasonListInfo> reasonList;


    public static void start(Activity context, OrderItem orderItem) {
        Intent intent = new Intent(context, CancelOrderActivity.class);
        intent.putExtra(ORDER_KEY, orderItem);
        Jumper.launchActivity(context, intent);
    }

    public void jumpCancelDetail() {
        if (mOrderInfo != null) {
            if (LoginInstance.getInstance().getUserInfo().isTravel()) {
                TrackUtil.trackScreenName("/booking/summary/cancellation/policy/" + mOrderInfo.getStatus());
            } else {
                TrackUtil.trackScreenName("/insider/booking/summary/cancellation/policy/" + mOrderInfo.getStatus());
            }
        }
        if (LoginInstance.getInstance().getUserInfo().isTravel()) {
            WebViewProxy.getInstance().browseWeb(this, H5UrlMaker.getCancelTravellerUrl());
        } else {
            WebViewProxy.getInstance().browseWeb(this, H5UrlMaker.getCancelInsiderUrl());
        }
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        int status = mOrderInfo.getStatus();
        switch (status) {
            case 1:
            case 2:
                serviceInfoLayout.setVisibility(View.GONE);
                refundTerm.setVisibility(View.GONE);
                break;

            case 3:
            case 4:
            case 5:
                if (LoginInstance.getInstance().getUserInfo().isTravel()) {
                    serviceInfoLayout.setVisibility(View.VISIBLE);
                } else {
                    serviceInfoLayout.setVisibility(View.GONE);
                }
                refundTerm.setVisibility(View.VISIBLE);
                break;
        }

    }

    protected void onCreate(Bundle savedInstanceState) {
        Intent intent = getIntent();
        if (intent == null) {
            finish();
            return;
        }
        mOrderInfo = (OrderItem) intent.getSerializableExtra(ORDER_KEY);
        if (mOrderInfo == null) {
            finish();
            return;
        }
        /**
         * ("1",//旅行者支付前取消原因
         ("2", //旅行者支付后取消原因
         ("3",  //发现者支付前取消原因
         ("4",  //发现者支付后取消原因
         */
        if (LoginInstance.getInstance().getUserInfo().isTravel()) {
            //旅行者
            if (mOrderInfo.getStatus() == 0 || mOrderInfo.getStatus() == 1 || mOrderInfo.getStatus() == 2) {
                type = "1";
            } else {
                type = "2";
            }
        } else {
            if (mOrderInfo.getStatus() == 0 || mOrderInfo.getStatus() == 1 || mOrderInfo.getStatus() == 2) {
                type = "3";
            } else {
                type = "4";
            }
            //发现者
        }

        // type=LoginInstance.getInstance().getUserInfo().isTravel()?"1":"2";
        OrderBusiness.getCancelReason(mApiProxy, type);
        super.onCreate(savedInstanceState, R.layout.ct_order_cancel);
    }

    @Override
    public void initListener() {
        cancelOrder.setOnClickListener(this);
        refundTerm.setOnClickListener(this);

        titleLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (flag) {
                    paidFee.setVisibility(View.GONE);
                    cancellationFee.setVisibility(View.GONE);
                    arrowIcon.setText(getString(R.string.arrow_down_icon));
                    flag = false;
                } else {
                    paidFee.setVisibility(View.VISIBLE);
                    cancellationFee.setVisibility(View.VISIBLE);
                    arrowIcon.setText(getString(R.string.arrow_up_icon));
                    flag = true;
                }
            }
        });

        mServiceLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ServiceDetailActivity.start(v.getContext(), mOrderInfo.getOid(), ServiceDetailActivity.SNAPSHOT);
            }
        });
    }

    @Override
    public void initData() {
        //行程简述
        ImageHelper.displayCtImage(mOrderInfo.getServicePIC(), servicePic, ImageHelper.getPersonDisplayImageOptions());
        serviceName.setText(mOrderInfo.getServiceName());
        String serviceAddress = mOrderInfo.getServiceAddress();
        simpleInfo.setText(serviceAddress);
        requestRefundInfo();

    }

    private void requestRefundInfo() {
        showLoading();
        OrderBusiness.getRefundInfo(mApiProxy, mOrderInfo.getOid());
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.cancel_order:
                if ((listViewReasons.getCheckedItemPosition() == reasonList.size() - 1)) {
                    if (TextUtils.isEmpty(otherReason.getText())) {
                        Utils.shakeView(otherReason);
                    } else {
                        msg = otherReason.getText().toString();
                        cancelOrder(msg);
                    }
                } else {
                    cancelOrder(msg);
                }

                break;

            case R.id.refund_term:
                jumpCancelDetail();
                break;

        }
    }


    private void cancelOrder(String msg) {
        showNoCancelDialog();
        LogHelper.e("cancel order", "" + mOrderInfo.getOid());
        OrderBusiness.cancelOrder(mApiProxy, mOrderInfo.getOid(), msg);
    }

    @Override
    public boolean onProxyResult(ProxyResult<?> result) {
        CtApiResponse response = (CtApiResponse) result.getData();
        if (ApiManager.GET_REFUND_INFO.equals(response.getApiName())) {
            hideLoading();
            if (response.isResponseNormal()) {
                if (response.result instanceof RefundInfo) {
                    RefundInfo refundInfo = (RefundInfo) response.result;
                    if (mOrderInfo.getStatus() == OrderItem.STATUS_WAIT_CONFIRM || mOrderInfo.getStatus() == OrderItem.STATUS_WAIT_PAY) {
                        refundInfo.setOrderPrice("0.00");
                        refundInfo.setRefundFee("0.00");
                        refundInfo.setCancelFee("0.00");
                    } else {
                        moneyType.setText(mOrderInfo.getPayCurrency());
                    }
                    servicePartViewHolder.build(CancelOrderActivity.this.getWindow().getDecorView());
                    servicePartViewHolder.render(FeeRenderData.getInstance(refundInfo));
                }
            }
        } else if (ApiManager.CANCEL_ORDER.equals(response.getApiName())) {
            hideNoCancelDialog();
            if (response.isResponseNormal()) {
                CtUserInfo userInfo = LoginInstance.getInstance().getUserInfo();
                if (userInfo != null) {
                    InputTime inputTime = InputTime.build(mOrderInfo.getServiceDate(), TimeUtil.getZeroZone());
                    String formatCommonTime = TimeUtil.formatTime(inputTime, OutputTime.getInstance(OutputTime.OutputType.TYPE_COMMON_ENGLISH, TimeUtil.getZeroZone()));

                    CTInformationNotificationMessage message = CtRongInfoProxy.getInstance().getCommonOrderChangeMessage(CtInfoNotificationMsgItemProvider.CtParamKey.BOOK_MSG_CANCELLED,
                            userInfo.getNick(), inputTime.getTime(), formatCommonTime);
                    CtRongInfoProxy.getInstance().sendSystemMessage(mOrderInfo.getTargetId(), message, null);
                }
                sendBroadcast(
                        new Intent(OrderItem.ORDER_STATUS_CHANGED_ACTION));

                final boolean isTraveller = LoginInstance.getInstance().getUserInfo().isTravel();
                SubmitSuccessModel.ContentType type = SubmitSuccessModel.ContentType.CANCEL_ORDER;
                String actionText = isTraveller
                        ? getString(R.string.operation_continue_exploring)
                        : getString(R.string.operation_view_book);
                String title = ResourceUtil.getString(R.string.book_operation_cancel_feedback_suc);

                SubmitSuccessModel submitSuccessModel = new SubmitSuccessModel(type, title, null, actionText);
                SubmitSuccessActivity.launchSuccessPage(this, submitSuccessModel);

                finish();
            } else {
                if (response != null && !TextUtils.isEmpty(response.msg)) {
                    MessageUtils.showToast(response.msg);
                }
            }

        } else if (ApiManager.GET_CANCEL_REASON.equals(response.getApiName())) {
            hideNoCancelDialog();
            if (response.isResponseNormal()) {
                if (response.result instanceof CancelReason) {
                    CancelReason reason = (CancelReason) response.result;
                    reasonList = reason.getReasonList();
                    ReasonListInfo reasonListInfo = new ReasonListInfo();
                    reasonListInfo.setKey("other");
                    reasonListInfo.setValue(getString(R.string.book_cancellation_resaon));
                    reasonList.add(reasonList.size(), reasonListInfo);
                    termSelectAdapter = new TermSelectAdapter();
                    listViewReasons.setAdapter(termSelectAdapter);
                    listViewReasons.setItemChecked(0, true);
                    msg = reasonList.get(0).getKey();
                    /*todo*/
                    // msg=reasons.get(0);
                    cancelOrder.setEnabled(true);
                    final InputMethodManager imm = (InputMethodManager) getBaseContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    listViewReasons.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            if (position == reasonList.size() - 1) {
                                otherReason.setVisibility(View.VISIBLE);
                                otherReason.setFocusable(true);
                                otherReason.setFocusableInTouchMode(true);
                                otherReason.requestFocus();
                                imm.showSoftInput(otherReason, InputMethodManager.SHOW_IMPLICIT);
//                                msg=otherReason.getText().toString();
                            } else {
                                imm.hideSoftInputFromInputMethod(otherReason.getWindowToken(), 0);
                                otherReason.setVisibility(View.GONE);
                                msg = reasonList.get(position).getKey();
                            }

                            termSelectAdapter.notifyDataSetChanged();
                        }
                    });
                }
            }
        }
        return false;
    }

    @Override
    public void onTopbarLeftPress() {
        finish();
    }

    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig config = new CustomUiConfig();
        config.mTopbarMiddleAreaName = getResources().getString(R.string.book_cancellation);
        config.mTopbarLeftAreaName = getString(R.string.back_icon);
        return config;
    }

    public class TermSelectAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return reasonList.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder = null;
            if (convertView == null) {
                convertView = LayoutInflater.from(getBaseContext()).inflate(R.layout.choice_term, parent, false);
                viewHolder = new ViewHolder();
                viewHolder.icon = (IconTextView) convertView.findViewById(R.id.icon);
                viewHolder.term = (TextView) convertView.findViewById(R.id.description);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            if (position == 0) {
                viewHolder.icon.setText(getString(R.string.correct_icon));
                viewHolder.icon.setTextColor(ResourceUtil.getColor(R.color.apple_7ecc1e));
            }

            viewHolder.icon.setText(listViewReasons.isItemChecked(position) ? getString(R.string.correct_icon) : getString(R.string.unselected_icon));
            viewHolder.icon.setTextColor(listViewReasons.isItemChecked(position) ? ResourceUtil.getColor(R.color.apple_7ecc1e) : ResourceUtil.getColor(R.color.ganshi_ded8d7));
            viewHolder.term.setText(reasonList.get(position).getValue());
            return convertView;
        }

        class ViewHolder {
            IconTextView icon;
            TextView term;
        }
    }
}
